package com.tianshi.yingxue.controller;

import com.aliyun.oss.OSS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.tianshi.yingxue.page.Result;
import java.io.File;
import java.io.IOException;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
@RestController
@RequestMapping("/video")
public class FileUploadController {

    @Autowired
    private OSS ossClient;

    @Value("${aliyun.oss.bucket-name}")
    private String bucketName;

    @Value("${aliyun.oss.video-folder}")
    private String videoFolder;

    @Value("${aliyun.oss.cover-folder}")
    private String coverFolder;

    @PostMapping("/uploadVideo")
    public Result uploadVideo(@RequestParam("videoFile") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.fail("请选择要上传的视频文件");
        }

        try {
            // 验证文件类型和大小
            validateFile(file, "video/", 100 * 1024 * 1024);

            // 生成OSS对象key
            String fileKey = videoFolder + generateFileName(file.getOriginalFilename());

            // 上传到OSS
            ossClient.putObject(bucketName, fileKey, file.getInputStream());

            // 返回访问URL（有效期1小时，生产环境应该配置更长的有效期或使用CDN域名）
            String url = ossClient.generatePresignedUrl(bucketName, fileKey,
                    Date.from(Instant.now().plus(1, ChronoUnit.HOURS))).toString();

            Map<String, String> data = new HashMap<>();
            data.put("videoPath", url);
            return Result.success("视频上传成功", data);

        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("视频上传失败: " + e.getMessage());
        }
    }

    @PostMapping("/uploadCover")
    public Result uploadCover(@RequestParam("coverFile") MultipartFile file) {
        if (file.isEmpty()) {
            return Result.fail("请选择要上传的封面图片");
        }

        try {
            // 验证文件类型和大小
            validateFile(file, "image/", 500 * 1024);

            // 生成OSS对象key
            String fileKey = coverFolder + generateFileName(file.getOriginalFilename());

            // 上传到OSS
            ossClient.putObject(bucketName, fileKey, file.getInputStream());

            // 返回访问URL
            String url = ossClient.generatePresignedUrl(bucketName, fileKey,
                    Date.from(Instant.now().plus(1, ChronoUnit.HOURS))).toString();

            Map<String, String> data = new HashMap<>();
            data.put("coverPath", url);
            return Result.success("封面上传成功", data);

        } catch (Exception e) {
            e.printStackTrace();
            return Result.fail("封面上传失败: " + e.getMessage());
        }
    }

    private void validateFile(MultipartFile file, String expectedType, long maxSize) {
        // 验证文件类型
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith(expectedType)) {
            throw new IllegalArgumentException("文件类型不匹配，期望" + expectedType);
        }

        // 验证文件大小
        if (file.getSize() > maxSize) {
            throw new IllegalArgumentException("文件大小不能超过" + (maxSize/1024) + "KB");
        }
    }

    private String generateFileName(String originalFilename) {
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        return UUID.randomUUID().toString() + extension;
    }
}
